package com.daxue.configtest.config;

import com.daxue.configtest.domian.RemoteConfig;
import com.daxue.configtest.exception.ServiceException;
import com.daxue.configtest.service.RemoteConfigService;
import com.daxue.configtest.utils.Query;
import com.daxue.configtest.utils.RemoteConfigUtils;
import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.environment.PropertySource;
import org.springframework.cloud.config.server.environment.EnvironmentRepository;
import org.springframework.context.ApplicationContextException;
import org.springframework.core.Ordered;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author daxue0929
 * @date 2023/3/25
 */

public class LocalEnvironmentRepository implements EnvironmentRepository, Ordered {

    private final RemoteConfigService remoteConfigService;

    private final int order;

    public LocalEnvironmentRepository(
        final RemoteConfigService remoteConfigService,
        final LocalEnvironmentProperties environmentProperties)
    {
        this.remoteConfigService = remoteConfigService;
        this.order = environmentProperties.getOrder();
    }

    @Override
    public Environment findOne(
        final String application, final String profile, final String label) {
        List<String> apps = Arrays.asList(StringUtils.commaDelimitedListToStringArray(application));
        Collections.reverse(apps);
        Environment result = new Environment(application, profile);
        for (String app : apps) {
            try {
                // label 传 null 时，readOne 会报错
                RemoteConfig config = remoteConfigService.readOne(Query.of("app").eq(app)
                    .and("env").eq(profile)
                    .and("label").eq(label).gen()
                );
                result.setLabel(label);
                result.add(new PropertySource(app, RemoteConfigUtils.convert(config)));
            } catch (ServiceException e) {
                throw new ApplicationContextException("failed to load local environment", e);
            }
        }
        return result;
    }

    @Override
    public int getOrder() {
        return this.order;
    }
}
